#!/usr/bin/env bash
set -eux
arch=x86_64
build_type=opt
cross_compile=
j=
outdir="$(pwd)"
while getopts a:c:j:o:t: OPT; do
  case "$OPT" in
    a)
      arch="$OPTARG"
      ;;
    c)
      cross_compile="CROSS_COMPILE=$OPTARG"
      ;;
    j)
      j="$OPTARG"
      ;;
    o)
      outdir="$OPTARG"
      ;;
    t)
      build_type="$OPTARG"
      ;;
    ?)
      exit 2
      ;;
  esac
done
shift "$(($OPTIND - 1))"
if [ -z "$j" ]; then
  j="$(nproc)"
fi
system_dir="${outdir}/system"
binaries_dir="${system_dir}/binaries"
disks_dir="${system_dir}/disks"
mkdir -p "$binaries_dir" "$disks_dir"
export PATH="/usr/lib/ccache:${PATH}"
if [ "$arch" = x86_64 ]; then
  scons -j "$j" --ignore-style "${outdir}/build/X86/gem5.${build_type}"
  f="${disks_dir}/linux-bigswap2.img"
  dd if=/dev/zero of="$f" bs=1024 count=65536
  mkswap "$f"
  # This file must always be present, despite --kernel overriding that default and selecting the kernel.
  # I'm not even joking. No one has ever built x86 gem5 without the magic dist dir present.
  touch "${binaries_dir}/x86_64-vmlinux-2.6.22.9"
elif [ "$arch" = arm ] || [ "$arch" = aarch64 ]; then
  scons -j "$j" --ignore-style "${outdir}/build/ARM/gem5.${build_type}"
  make -C ./system/arm/dt/
  mkdir -p "${system_dir}/arm/dt"
  # || true in case they are the same directory.
  cp ./system/arm/dt/*.dtb "${system_dir}/arm/dt" || true
  # TODO use the buildroot cross compiler here, and remove the dependencies from configure.
  make -C ./system/arm/simple_bootloader/ $cross_compile
  cp ./system/arm/simple_bootloader/boot_emm.arm "$binaries_dir"
  # TODO cross_compile is ignored because the make does not use CC...
  make -C ./system/arm/aarch64_bootloader/ $cross_compile
  cp ./system/arm/aarch64_bootloader/boot_emm.arm64 "$binaries_dir"
fi
make -C util/term
cp util/term/m5term "${outdir}"
